<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="父节点" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          placeholder="请选择父节点"
          :data="treeData"
          filterable
          check-strictly
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门领导">
        <user-select v-model="form.uid" filterable :data="userList" />
      </el-form-item>
      <el-form-item label="协管人员">
        <user-select
          v-model="form.leaders"
          multiple
          filterable
          :data="userList"
        />
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input v-model="form.sort" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit, doAdd } from '@/api/departmentManagement'
  import { getList } from '@/api/userManagement'

  export default defineComponent({
    name: 'DepartmentManagementEdit',
    components: {
      UserSelect: defineAsyncComponent(() =>
        import('@/components/biz/UserSelect')
      ),
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name',
        },
        list: [],
        form: {
          parentName: '',
          parentId: '',
        },
        rules: {
          parentId: [
            { required: true, trigger: 'change', message: '请选择父节点' },
          ],
          name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
          sort: [{ required: true, trigger: 'blur', message: '请输入排序' }],
        },
        title: '',
        dialogFormVisible: false,
        userList: [],
      })

      const getUserList = async () => {
        const params = {
          pageNum: 1,
          pageSize: 9999,
        }
        const {
          data: { list },
        } = await getList(params)
        state.userList = list || []
      }

      const handleNodeClick = (node) => {
        state.form.parentName = node.name
        state.form.parentId = `${node.id}`
      }
      const showEdit = (row, list) => {
        state.treeData = list
        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'
          const formData = JSON.parse(JSON.stringify(row))
          if (formData.leaders && formData.leaders.length) {
            formData.leaders = formData.leaders
              .split(',')
              .map((item) => Number(item))
          }
          state.form = formData
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          parentName: '',
          parentId: '',
        }
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            try {
              const params = JSON.parse(JSON.stringify(state.form))
              if (params.leaders && params.leaders.length) {
                params.leaders = params.leaders.join(',')
              }
              const { msg } =
                state.title === '添加'
                  ? await doAdd(params)
                  : await doEdit(params)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
            } catch (e) {
              console.log(e)
            }
          }
        })
      }

      onMounted(() => {
        getUserList()
      })

      return {
        ...toRefs(state),
        handleNodeClick,
        showEdit,
        close,
        save,
      }
    },
  })
</script>
